<?php

/**
 * User:ayou chow
 * Date: 2019-11-19
 * Time: 14:46
 */

namespace app\admin\controller;


use app\common\model\AdminModel;
use app\common\model\AdsModel;
use app\common\model\AgentModel;
use app\common\model\AnchorFansModel;
use app\common\model\AnchorReportModel;
use app\common\model\BlackDeviceModel;
use app\common\model\ExpertModel;
use app\common\model\GroupChatUserModel;
use app\common\model\LiveModel;
use app\common\model\LiveNoticeModel;
use app\common\model\LiveTicketLogModel;
use app\common\model\RegSourceModel;
use app\common\model\StatisticsModel;
use app\common\model\UserApplyModel;
use app\common\model\UserBackpackModel;
use app\common\model\UserBackpackStatistics;
use app\common\model\UserLevelRuleModel;
use app\common\model\UserLogModel;
use app\common\model\UserModel;
use app\common\model\AnchorBannedModel;
use app\common\model\LiveRoomManagerModel;
use app\common\model\LiveRoomBanneduserModel;
use app\common\model\UserPhotoModel;
use app\common\model\UserProfileModel;
use app\common\model\ConfigPubModel;
use app\common\model\ConfigTagModel;
use app\common\model\UserTicketLogModel;
use app\service\ChatService;
use app\service\UserService;
use gogrpc\AccountServer;
use gogrpc\LiveServer;
use think\Db;
use think\db\Query;
use think\facade\Cookie;
use think\facade\Request;
use itbdw\Ip\IpLocation;
use think\Validate;
use function Couchbase\defaultDecoder;
use think\facade\Cache;
use think\facade\Config;
use PHPRedis\Filters\BloomFilter;


class UserController extends BaseController
{


    public function index()
    {
        $source_key  = Request::get('source_key');
        $source_list = RegSourceModel::field('id,source_key,source_name')->select();
        $this->assign('source_key', $source_key);
        $this->assign('source_list', $source_list);

        $role = Cookie::get("roleid");
        $this->assign('role', $role);
        return $this->fetch();
    }

    public function add()
    {
        $this->assign('account_typearr', UserModel::ACCOUNT_TYPE);
        return $this->fetch();
    }

    public function edit()
    {
        $id        = Request::param("id");
        $userModel = UserModel::get($id);

        // 账号类型 1=用户，2-测试用户，3=主播，4=公司主播，5=测试主播
        $userModel->account_type   = UserModel::userAccountType($userModel->is_anchor, $userModel->anchor_type);
        $userModel->mobile         = mobileHide($userModel->mobile, $this->userinfo->roleid);
        $userModel->account        = mobileHide($userModel->account, $this->userinfo->roleid);
        $userModel->chat_admin_ids = explode(',', $userModel->chat_admin_ids);
        $tags = ConfigTagModel::select();

        //查询后台管理员
        $admin_list = AdminModel::where('status', 1)->field('id,name')->select();

        $this->assign("admin_list", $admin_list);
        $this->assign("userinfo", $userModel);
        $this->assign('account_typearr', UserModel::ACCOUNT_TYPE);
        $this->assign('tags', $tags);
        return $this->fetch();
    }

    public function fans_edit()
    {
        $id        = Request::param("id");
        $userModel = UserModel::get($id);
        $fans_count = AnchorFansModel::where('anchorid', $id)->count("id");
        $userModel->fans_count = $fans_count;
        $this->assign("userinfo", $userModel);
        return $this->fetch();
    }

    public function save_anchor_fans()
    {
        $id = Request::param("id");
        if ($id < 1) {
            return self::bulidFail('用户信息不存在');
        }
        $user = UserModel::get($id);
        if (empty($user)) {
            return self::bulidFail('用户信息不存在');
        }

        $fans_count = AnchorFansModel::where('anchorid', $id)->count("id");
        $user->fans_count = $fans_count;

        $fans_num = Request::param("fans_num");
        if ($fans_num <= $fans_count) {
            return self::bulidFail('设置数量必须大于当前粉丝数量');
        }

        // 查询当前粉丝 ID 列表
        $existing_fans = AnchorFansModel::where('anchorid', $id)->column('fansid');
        
        // 从 db_user 表中查询非现有粉丝的用户 ID
        $user_query = UserModel::whereNotIn('id', $existing_fans);
        $random_users = $user_query->orderRaw('RAND()')->limit($fans_num - $fans_count)->select();

        if (empty($random_users)) {
            return self::bulidFail('可用的用户数量不足');
        }

        // 准备插入数据
        $insert_data = [];
        foreach ($random_users as $user) {
            $insert_data[] = [
                'anchorid'    => $id,
                'fansid'      => $user->id,
                'create_time' => date('Y-m-d H:i:s'),
                'live_id'     => 0,
            ];
        }

        // 批量插入到 db_anchor_fans 表
        $res = AnchorFansModel::insertAll($insert_data);
        if ($res) {
            redis_del("FansCount_" . $id);
            return parent::bulidSuccess('操作成功');
        }
        return static::bulidFail();
    }

    public function report()
    {
        return $this->fetch();
    }

    public function roomAdmin()
    {
        return $this->fetch();
    }

    public function roomBanned()
    {
        $this->assign('ban_type', LiveRoomBanneduserModel::BAN_TYPE);
        return $this->fetch();
    }

    public function signForCos()
    {
        return parent::signForCos();
    }

    public function getlist()
    {
        $all = $this->getAllParams();
        // 状态类型 0不在线 1 在线，2封禁 3禁言
        $status_type = isset($all['online_status']) ? $all['online_status'] : '';

        $where = [];
        if (isset($all['start_time']) && $all['start_time']) {
            $where[] = ["regist_time", ">=", $all["start_time"]];
        }

        if (isset($all['end_time']) && $all['end_time']) {
            $where[] = ["regist_time", "<=", $all["end_time"]];
        }

        if (isset($all['mobile']) && $all['mobile']) {
            $where[] = ["mobile", "LIKE", $all["mobile"] . "%"];
        }
        if (isset($all['account']) && $all['account']) {
            $where[] = ["account", "LIKE", $all["account"] . "%"];
        }
        if (isset($all['nick_name']) && $all['nick_name']) {
            $where[] = ["nick_name", "LIKE", $all["nick_name"] . "%"];
        }
        // 注册ip
        if (isset($all['regist_ip']) && $all['regist_ip']) {
            $where[] = ["regist_ip", "LIKE", $all["regist_ip"] . "%"];
        }
        // 注册渠道
        if (isset($all['reg_source_id']) && $all['reg_source_id']) {
            $where[] = ["reg_source_id", "=", $all["reg_source_id"]];
        }

        if (isset($all['id']) && $all['id']) {
            if (is_numeric($all['id'])) {
                $where[] = ["id", "=", $all["id"]];
            } else {
                $where[] = ["id", "=", 0];
            }
        }

        // 设备编号
        if (isset($all['device_info']) && $all['device_info']) {
            $where[] = ["device_info", "=", $all["device_info"]];
        }


        if (isset($all['anchor_type'])) {
            if ($all["anchor_type"] == 0) {
                $where[] = ["is_anchor", "=", 0];
            } else if ($all['anchor_type'] == 4) {
                $where[] = ["anchor_type", "=", 3];
                $where[] = ["is_anchor", "=", 0];
            } else if ($all['anchor_type'] == 5) {
                // 查询房管
                $room_manager     = LiveRoomManagerModel::column('mgrid');
                $room_manager_ids = array_unique(array_filter($room_manager));
                if ($room_manager_ids) {
                    $where[] = ["id", "in", $room_manager_ids];
                } else {
                    $where[] = ["id", "=", 0];
                }
            } else {
                $where[] = ["anchor_type", "=", $all["anchor_type"]];
                $where[] = ["is_anchor", "=", 1];
            }
        }
        if (isset($all['regist_type']) && is_numeric($all['regist_type'])) {
            $where[] = ["regist_type", "=", $all["regist_type"]];
        }
        if (isset($all['expert_type']) && is_numeric($all['expert_type'])) {
            $where[] = ["expert_type", "=", $all["expert_type"]];
        }


        // 用户状态  0不在线 1在线 2封禁 3禁言  40:注销
        if (is_numeric($status_type) && in_array($status_type, [0, 1, 2, 3, 40])) {
            if ($status_type == 2) {
                $where[] = ["status", "=", 1];
            } else if ($status_type == 3) {
                // 禁言用户id
                $banned_uid = LiveRoomBanneduserModel::where('ban_time', '>=', time())->column('uid');
                if ($banned_uid) {
                    $where[] = ['id', 'in', $banned_uid];
                } else {
                    $where[] = ["id", "=", 0];
                }
            } else if ($status_type == 1) {
                $where[] = ['online_status', '=', $all["online_status"]];
            } else if ($status_type == 40) {
                $where[] = ['status', '=', 4];
            } else {
                $where[] = ['online_status', '<>', 1];
            }
        }

        $order = "regist_time desc";
        if (isset($all["field"]) && $all["field"] && isset($all["order"]) && $all["order"]) {
            $order = sprintf("%s %s", $all["field"], $all["order"]);
        }

        $page  = Request::param("page");
        $limit = Request::param("limit");

        $userlist = UserModel::where($where)->alias('u')
            ->with([
                'profile', 'roomAdmins', 'bannerdUser',
                'regsource' => function (Query $query) {
                    $query->field('id,source_key,source_name');
                },
                'noble'     => function (Query $query) {
                    $query->field('uid,anchor_id,expiration,create_time,from')->where('expiration', '>', time())->order('create_time', 'desc');
                },
                'recommend' => function (Query $query) {
                    $query->field('user_id,origin_anchor_id');
                }
            ])
            ->field('u.*,c.uid,c.count as checkin_count,c.continuous as checkin_continuous')
            ->leftJoin('db_user_checkin c', 'c.uid = u.id')
            ->page($page, $limit)
            ->order($order)
            ->select()
            ->toArray();

        if (count($userlist) > 0) {
            $count = UserModel::where($where)->count("id");
            $device_info = BlackDeviceModel::whereIn('device', array_column($userlist, 'device_info'))->column('device');
            foreach ($userlist as &$item) {
                $loc                 = IpLocation::getLocation($item["regist_ip"]);
                $item["regist_area"] = count($loc) > 2 ? $loc["area"] : '未知';
                $item['diamond']     = bcdiv(strval($item['diamond']), '100', 2);
                if ($item['diamond'] === '0.00') {
                    $item['diamond'] = '0';
                }
                $item['gold'] = bcdiv(strval($item['gold']), '100', 2);
                if ($item['gold'] === '0.00') {
                    $item['gold'] = '0';
                }
                $item["mobile"]  = mobileHide($item['mobile'], $this->userinfo->roleid);
                $item["account"] = mobileHide($item['account'], $this->userinfo->roleid);
                if (!empty($item['bannerd_user']) && $item['bannerd_user']['ban_time'] > 0 && $item['bannerd_user']['ban_time'] > time()) {
                } else {
                    if (isset($item['bannerd_user'])) {
                        if ($item['bannerd_user']['ban_time'] > 0) {
                            unset($item['bannerd_user']);
                        }
                    }
                }

                if ($item['device_info']) {
                    $item['device_status'] = in_array($item['device_info'], $device_info) ? 1 : 0;
                } else {
                    $item['device_status'] = 0;
                }
            }
            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function export()
    {

        $role = Cookie::get("roleid");
        if ($role != "11" && $role != "21") {
            die("无导出权限");
        }

        $all = $this->getAllParams();
        // 状态类型 0不在线 1 在线，2封禁 3禁言
        $status_type = isset($all['online_status']) ? $all['online_status'] : '';

        $where = [];
        if (isset($all['start_time']) && $all['start_time']) {
            $where[] = ["regist_time", ">=", $all["start_time"]];
        }

        if (isset($all['end_time']) && $all['end_time']) {
            $where[] = ["regist_time", "<=", $all["end_time"]];
        }

        if (isset($all['mobile']) && $all['mobile']) {
            $where[] = ["mobile", "LIKE", $all["mobile"] . "%"];
        }
        if (isset($all['account']) && $all['account']) {
            $where[] = ["account", "LIKE", $all["account"] . "%"];
        }
        if (isset($all['nick_name']) && $all['nick_name']) {
            $where[] = ["nick_name", "LIKE", $all["nick_name"] . "%"];
        }
        // 注册ip
        if (isset($all['regist_ip']) && $all['regist_ip']) {
            $where[] = ["regist_ip", "LIKE", $all["regist_ip"] . "%"];
        }
        // 注册渠道
        if (isset($all['reg_source_id']) && $all['reg_source_id']) {
            $where[] = ["reg_source_id", "=", $all["reg_source_id"]];
        }

        if (isset($all['id']) && $all['id']) {
            if (is_numeric($all['id'])) {
                $where[] = ["id", "=", $all["id"]];
            } else {
                $where[] = ["id", "=", 0];
            }
        }

        // 设备编号
        if (isset($all['device_info']) && $all['device_info']) {
            $where[] = ["device_info", "=", $all["device_info"]];
        }


        if (isset($all['anchor_type'])) {
            if ($all["anchor_type"] == 0) {
                $where[] = ["is_anchor", "=", 0];
            } else if ($all['anchor_type'] == 4) {
                $where[] = ["anchor_type", "=", 3];
                $where[] = ["is_anchor", "=", 0];
            } else if ($all['anchor_type'] == 5) {
                // 查询房管
                $room_manager     = LiveRoomManagerModel::column('mgrid');
                $room_manager_ids = array_unique(array_filter($room_manager));
                if ($room_manager_ids) {
                    $where[] = ["id", "in", $room_manager_ids];
                } else {
                    $where[] = ["id", "=", 0];
                }
            } else {
                $where[] = ["anchor_type", "=", $all["anchor_type"]];
                $where[] = ["is_anchor", "=", 1];
            }
        }
        if (isset($all['regist_type']) && is_numeric($all['regist_type'])) {
            $where[] = ["regist_type", "=", $all["regist_type"]];
        }
        if (isset($all['expert_type']) && is_numeric($all['expert_type'])) {
            $where[] = ["expert_type", "=", $all["expert_type"]];
        }


        // 用户状态  0不在线 1在线 2封禁 3禁言  40:注销
        if (is_numeric($status_type) && in_array($status_type, [0, 1, 2, 3, 40])) {
            if ($status_type == 2) {
                $where[] = ["status", "=", 1];
            } else if ($status_type == 3) {
                // 禁言用户id
                $banned_uid = LiveRoomBanneduserModel::where('ban_time', '>=', time())->column('uid');
                if ($banned_uid) {
                    $where[] = ['id', 'in', $banned_uid];
                } else {
                    $where[] = ["id", "=", 0];
                }
            } else if ($status_type == 1) {
                $where[] = ['online_status', '=', $all["online_status"]];
            } else if ($status_type == 40) {
                $where[] = ['status', '=', 4];
            } else {
                $where[] = ['online_status', '<>', 1];
            }
        }

        $order = "regist_time desc";
        if (isset($all["field"]) && $all["field"] && isset($all["order"]) && $all["order"]) {
            $order = sprintf("%s %s", $all["field"], $all["order"]);
        }

        $userlist = UserModel::where($where)->alias('u')
            ->with([
                'profile', 'roomAdmins', 'bannerdUser',
                'regsource' => function (Query $query) {
                    $query->field('id,source_key,source_name');
                },
                'noble'     => function (Query $query) {
                    $query->field('uid,anchor_id,expiration,create_time,from')->where('expiration', '>', time())->order('create_time', 'desc');
                },
                'recommend' => function (Query $query) {
                    $query->field('user_id,origin_anchor_id');
                }
            ])
            ->field('u.*,c.uid,c.count as checkin_count,c.continuous as checkin_continuous')
            ->leftJoin('db_user_checkin c', 'c.uid = u.id')
            ->order($order)
            ->select()
            ->toArray();

        if (count($userlist) > 0) {
            foreach ($userlist as &$item) {
                $loc                 = IpLocation::getLocation($item["regist_ip"]);
                $item["regist_area"] = count($loc) > 2 ? $loc["area"] : '未知';
            }
        }
        $exports = [];

        if (count($userlist) > 0) {
            foreach ($userlist as &$item) {
                $exports[] = [
                    $item['id'],
                    $item['mobile'],
                    $item['regist_area'],
                    $item['regist_time'],
                ];
            }
        }

        if (empty($exports)) {
            $this->error('没有相关数据');
        }

        $file_title = ['ID', '手机号码', '注册地区', '注册时间'];
        $file_name  = '用户导出' . date('Y年m月d日H点');

        // 记录日志
        parent::addAdminLog('导出用户表');

        return export_excel($exports, $file_title, $file_name, '用户导出');
    }

    public function online()
    {
        if ($this->request->isAjax()) {
            $pageIndex = (int)$this->get('page', 1);
            $pageSize  = (int)$this->get('limit', 20);

            $model          = UserModel::field('*');
            $id             = $this->get('id', 0);
            $account        = $this->get('account', '');
            $nick_name      = $this->get('nick_name', '');
            $mobile         = $this->get('mobile', '');
            $login_platform = $this->get('login_platform', '');

            if ($id && is_numeric($id)) {
                $model = $model->where('id', $id);
            } else if ($account) {
                $model = $model->where('account', $account);
            } else if ($mobile && is_numeric($mobile)) {
                $model = $model->where('mobile', $mobile);
            } else {
                if ($nick_name) {
                    $model = $model->whereLike('nick_name', $nick_name . '%');
                }

                if (($reg_source_id = trim($this->get('reg_source_id', ''))) && is_numeric($reg_source_id)) {
                    $model = $model->where('reg_source_id', $reg_source_id);
                }

                if (in_array($login_platform, ['0', 1, 2])) {
                    $model = $model->where('login_platform', $login_platform);
                }
            }

            // 角色id
            $admin_roleid = $this->userinfo->roleid;

            $model = $model->where('online_status', 1);
            return json([
                'count' => $model->count(),
                'list'  => $model->order('id', 'desc')
                    ->page($pageIndex, $pageSize)
                    ->select()
                    ->each(function ($query) use ($admin_roleid) {
                        $query->mobile  = mobileHide($query->mobile, $admin_roleid);
                        $query->account = mobileHide($query->account, $admin_roleid);
                    })
                    ->toArray(),
                'code'  => 0,
                //'sql' => $model->getLastSql()
            ]);
        }

        $source = RegSourceModel::field('id,url')->select()->toArray();
        foreach ($source as $key => $value) {
            if (!$value['url']) {
                unset($source[$key]);
            }
        }
        return $this->assign([
            'source'      => $source,
            'source_json' => json_encode(array_column($source, 'url', 'id'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
        ])->fetch();
    }

    public function kicked_out()
    {
        $id = Request::get("id");
        if ($id < 1) {
            return self::bulidFail('用户信息不存在');
        }

        $user = UserModel::get($id);
        if (empty($user)) {
            return self::bulidFail('用户信息不存在');
        }

        // 判断用户是否正在直播中
        $is_live = LiveModel::where('anchorid', $id)->field('id')->find();
        if ($is_live) {
            return self::bulidFail('该用户正在直播中，不可踢出');
        }

        $account_server = new AccountServer();
        $res            = $account_server->logout($id);
        if ($res) {
            parent::addAdminLog('踢出在线用户,uid:' . $id, $id);
            return parent::bulidSuccess('踢出成功');
        }
        return static::bulidFail();
    }

    public function setAdminShow()
    {
        $id   = Request::get("id");
        $user = UserModel::where("id", $id)->with(['profile', 'roomAdmins', 'bannerdUser'])->find();
        $type = isset($user["roomAdmins"]) ? $user["roomAdmins"]["type"] : -1;
        return view("setAdminShow", [
            "userinfo"       => $user,
            "roomAdminsType" => $type,
        ]);
    }

    public function setBanTime()
    {
        $id      = Request::get("id");
        $room_id = Request::get("room_id", 0, 'intval');
        $chat_id = Request::get("chat_id", 0, 'intval');
        // 1用户列表、2=聊天日志，3=聊天监控
        $type = Request::get('type');

        $user = UserModel::where("id", $id)->with([
            'nobleRecord' => function ($query) {
                $where = [['expiration', '>=', time()]];
                $query->where($where)->order('id DESC')->limit(1);
            }
        ])->find();

        if (!$user) {
            $this->error('访问信息不存在');
        }

        $user->nobel_str = !empty($user->noble_record->noble) ? $user->noble_record->noble->name : '';

        // 用户等级计算
        $user->user_level = UserLevelRuleModel::getUserLevel($user->point);

        //禁言原因
        $ban_type = LiveRoomBanneduserModel::BAN_TYPE;
        if (isset($ban_type[9])) {
            unset($ban_type[9]);
        }

        $ban_time = isset($user["bannerdUser"]) ? $user["bannerdUser"]["ban_time"] : -1;
        return view("setBanTime", [
            "userinfo" => $user,
            "type"     => $type,
            "ban_type" => $ban_type,
            "room_id"  => $room_id,
            "ban_time" => $ban_time,
            "chat_id"  => $chat_id,
        ]);
    }


    /**
     * 添加用户业务处理
     * @return \think\response\Json
     */
    public function add_post()
    {
        $all_request = Request::param();
        // 账号类型
        $account_type = Request::param('account_type');

        // 账号类型配置
        $acctype_arr_str = implode(',', array_keys(UserModel::ACCOUNT_TYPE));

        $validate = new Validate([
            'password'     => 'require|length:6,12|pass:' . config('other.alpha_num'),
            // 'mobile'       => 'require|pass:' . config('other.mobile_preg'),
            // 'nick_name'    => 'length:2,8|chsDash',
            'gender'       => 'in:1,2',
            'account_type' => "number|in:$acctype_arr_str",
            'expert_type'  => "number|in:0,1,2",
        ], [
            "password.require"    => "请输入密码",
            "password.length"     => "密码必须在6-12位之间",
            "password.pass"       => "密码必须为字母和数字",
            // "mobile.require"      => "请输入手机号",
            // "mobile.pass"         => "请输入正确的手机号",
            // "nick_name.length"    => "昵称长度在2-8个字符",
            "nick_name.chsDash"   => "昵称只能是汉字、字母或数字或中划线或下划线",
            "gender.in"           => "性别选择错误",
            "account_type.number" => "账号类型选择错误",
            "account_type.in"     => "账号类型选择错误",
            "expert_type"         => "专家角色选择错误",
        ]);

        if (!$validate->check($all_request)) {
            return self::bulidFail($validate->getError());
        }

        $userModel = new UserModel($all_request);

        $userProfileModel   = new UserProfileModel($all_request);
        $find_account_where = [
            "mobile" => $userModel->mobile
        ];
        //检测手机号是否占用
        $checkUser = UserModel::where($find_account_where)->find();
        if ($checkUser) {
            return self::bulidFail("手机号已被占用");
        }

        if ($userModel->nick_name) {
            $check_nickname = UserModel::where('nick_name', $userModel->nick_name)->field('id')->find();
            if (!empty($check_nickname)) {
                return self::bulidFail("昵称：" . $userModel->nick_name . "已存在");
            }
        }

        if (!isset($all_request["password"]) && $all_request["password"]) {
            return self::bulidFail("请输入密码");
        }

        $userModel->account     = $userModel->mobile;
        $userModel->password    = openssl_encrypt(substr($userModel->account, strlen($userModel->account) - 4, 4) . $all_request["password"], "DES-ECB", $this->OPENSSL_KEY);
        $userModel->regist_time = date("Y-m-d H:i:s");
        $userModel->last_login  = date("Y-m-d H:i:s");


        if (!isset($userModel["avatar"]) || !$userModel["avatar"]) {
            // 写入默认头像地址
            //            $userModel->avatar = ConfigPubModel::field("default_avatar_url")->find()['default_avatar_url'];
            $thumbs = array();
            if ($userModel->expert_type > 0) {
                $thumbs = AdsModel::where(["status" => 1, "type" => 9, 'role_type' => 2])->select()->toArray();
            }
            if (empty($thumbs)) {
                $thumbs = AdsModel::where(["status" => 1, "type" => 9, 'role_type' => 1])->select()->toArray();
            }
            if (empty($thumbs)) {
                return self::bulidFail("没有相关默认头像，请先配置默认头像");
            }

            $thumb             = $thumbs[array_rand($thumbs, 1)];
            $userModel->avatar = $thumb["image_url"];
        }
        $userModel->regist_type = 0;
        $userModel->regist_ip   = get_client_ip();

        // 主播账号
        if (in_array($account_type, [3, 4, 5])) {
            // $userModel->anchor_secret = md5(uniqid() . time());
            $userModel->auth_time     = date("Y-m-d H:i:s");
            $userModel->sharing_ratio = 40;
        }

        // 更改账号类型字段
        switch ($account_type) {
            case 1;
                $userModel->is_anchor   = 0;
                $userModel->anchor_type = 1;
                break;
            case 2;
                $userModel->is_anchor   = 0;
                $userModel->anchor_type = 3;
                break;
            case 3;
                $userModel->is_anchor   = 1;
                $userModel->anchor_type = 1;
                break;
            case 4;
                $userModel->is_anchor   = 1;
                $userModel->anchor_type = 2;
                break;
            case 5;
                $userModel->is_anchor   = 1;
                $userModel->anchor_type = 3;
                break;
        }

        Db::startTrans();
        try {
            if (!$userModel->save()) {
                throw new \Exception('添加信息失败');
            }

            if (empty($userModel->nick_name)) {
                $userModel->nick_name = "龙门" . $userModel->id;
                $userModel->save();
            }

            // 用户基础表
            $userProfileModel->uid    = $userModel->id;
            $userProfileModel->gender = isset($all_request['gender']) ? $all_request['gender'] : 0;

            if (!$userProfileModel->save()) {
                throw new \Exception('添加信息失败');
            }

            $agent = new AgentModel([
                'uid'               => $userModel->id,
                'profit'            => 0,
                'total_profit'      => 0,
                'diamond'           => 0,
                'withdrawn_diamond' => 0,
                'invite_code'       => createInviteCode(),
                'created_time'      => time()
            ]);
            if (!$agent->save()) {
                throw new \Exception('添加代理信息失败');
            }

            //保存封面图
            $photoModel = new UserPhotoModel([
                'uid'         => $userModel->id,
                'img_url'     => Request::param("cover_image"),
                'is_cover'    => 1,
                'create_time' => date("Y-m-d H:i:s"),
            ]);
            if (!$photoModel->save()) {
                throw new \Exception('添加信息失败');
            }

            // 如果是专家角色，添加基本信息到专家表中
            if ($userModel->expert_type > 0) {
                //检测昵称是否存在
                $check_nickname = ExpertModel::where('nick_name', $userModel->nick_name)->field('id')->find();
                if (!empty($check_nickname)) {
                    throw new \Exception('专家昵称已存在，请更换');
                }
                $expert_obj = new ExpertModel([
                    'user_id'     => $userModel->id,
                    'profile'     => $userModel->avatar,
                    'nick_name'   => $userModel->nick_name,
                    'create_time' => time(),
                    'grade'       => 1,
                    'admin_id'    => $this->admin_id,
                ]);
                if (!$expert_obj->save()) {
                    throw new \Exception('添加信息失败');
                }
            }

            // 增加累计注册数据
            if (empty(StatisticsModel::setRegistPcNum())) {
                throw new \Exception('pc注册数增加错误');
            }

            // 设置es 主播数据
            if ($userModel->is_anchor == 1) {
                $res = UserService::setAnchorEs($userModel->id);
                if ($res['code'] != 0) {
                    throw new \Exception('添加信息失败');
                }
            }

            Db::commit();

            // 清理主播缓存
            if ($userModel->is_anchor == 1) {
                UserModel::delAnchorCache();
            }
            // 记录日志
            $log_content = "添加用户信息，用户ID：{$userModel->id}，登录账号：{$userModel->account}";
            parent::addAdminLog($log_content, $userModel->id);
            // add redis 
            $bloomFilter = new BloomFilter(Config::get('cache.redis'));
            $bloomFilter->setAuth(Config::get('cache.redis.password'));
            $bloomFilter->add('mobile', $userModel->account);
            $bloomFilter->add('id', $userModel->id);

            return self::bulidSuccess([], "添加用户成功");
        } catch (\Exception $e) {
            Db::rollback();
            return self::bulidDataFail(['error' => $e->getMessage()], '添加信息失败');
        }
    }

    public function edit_post()
    {
        $id        = Request::param("id");
        $mobile    = Request::param("mobile");
        $nick_name = Request::param("nick_name");
        $avatar    = Request::param("avatar");
        $pwd       = Request::param("password");
        // 专家角色
        $expert_type = Request::param("expert_type");
        // 账号类型
        $account_type = Request::param("account_type");
        // 分成比例
        $sharing_ratio = Request::param("sharing_ratio", 0, 'intval');
        // 修改备注
        $remark = Request::param("remark");
        // 私聊人员id
        $chat_admin_ids = Request::param("chat_admin_ids");
        $tags = Request::param("tags");
        $intro = Request::param("intro");
        $banner = Request::param("banner");
        $replay_show = Request::param("replay_show");


        $acctype_arr_str = implode(',', array_keys(UserModel::ACCOUNT_TYPE));
        $validate        = new Validate([
            // 'mobile'        => 'require|pass:' . config('other.mobile_preg'),
            'nick_name'     => 'require|length:2,20|chsDash',
            'remark'        => 'max:64',
            'password'      => 'length:6,12|pass:' . config('other.alpha_num'),
            'account_type'  => "number|in:$acctype_arr_str",
            'is_guess_host' => 'require|number|in:0,1',
        ], [
            // "mobile"           => "请输入正确的手机号",
            "nick_name.require"     => "请输入昵称",
            "nick_name.length"      => "昵称长度在2-8个字符",
            "nick_name.chsDash"     => "昵称只能是汉字、字母或数字或中划线或下划线",
            "password.length"       => "密码必须在6-12位之间",
            "password.pass"         => "密码必须为字母和数字",
            "remark.max"            => "备注最多不超过64个字符",
            "account_type.number"   => "账号类型选择错误",
            "account_type.in"       => "账号类型选择错误",
            'is_guess_host.require' => '竞猜权限必须',
            'is_guess_host.number'  => '竞猜权限类型错误',
            'is_guess_host.in'      => '竞猜权限取值错误',
        ]);

        if (!$validate->check(Request::param())) {
            return self::bulidFail($validate->getError());
        }

        //分红数值验证
        $anchor_account_typearr = [3, 4, 5];
        if (in_array($account_type, $anchor_account_typearr) && ($sharing_ratio < 1 || $sharing_ratio > 100)) {
            return self::bulidFail("分成比例不得大于100且不小于1");
        }

        $userModel = UserModel::get($id);
        if (!$userModel) {
            return self::bulidFail("用户不存在");
        }

        // 检测手机号是否存在
        // $find_mobile_where = [['id', '<>', $id], ['mobile', '=', $mobile]];
        // $check_mobile      = UserModel::where($find_mobile_where)->field('id')->find();
        // if (!empty($check_mobile)) {
        //     return self::bulidFail("手机号已被占用");
        // }

        // 检测昵称是否存在
        $find_nickname_where = [['id', '<>', $id], ['nick_name', '=', $nick_name]];
        $check_nickname      = UserModel::where($find_nickname_where)->field('id')->find();
        if (!empty($check_nickname)) {
            return self::bulidFail("昵称已被占用");
        }

        // 当前用户账号类型
        $old_account_type = UserModel::userAccountType($userModel->is_anchor, $userModel->anchor_type);

        $userModel->is_guess_host  = $this->post('is_guess_host');
        $userModel->chat_admin_ids = rtrim($chat_admin_ids, ',');

        // 如果是超管直接修改
        if ($this->userinfo->roleid == 1 || $this->userinfo->roleid == 11) {
            // $userModel->mobile    = $mobile;
            $userModel->nick_name = $nick_name;
            $userModel->avatar    = $avatar;
            $userModel->intro    = $intro;
            $userModel->banner    = $banner;
            $userModel->replay_show    = $replay_show;
            if ($pwd) {
                $userModel->password = openssl_encrypt(substr($userModel->account, strlen($userModel->account) - 4, 4) . $pwd, "DES-ECB", $this->OPENSSL_KEY);;
            }

            // 主播账号类型数组  如果原始数据用户不是主播，修改成主播的
            if (in_array($account_type, $anchor_account_typearr)) {
                if (!in_array($old_account_type, $anchor_account_typearr)) {
                    // 秘钥为空则生成一个
                    // $userModel->anchor_secret = empty($userModel->anchor_secret) ? md5(uniqid() . time()) : $userModel->anchor_secret;
                    $userModel->auth_time = strtotime($userModel->auth_time) <= 0 ? date("Y-m-d H:i:s") : $userModel->auth_time;
                }
                $userModel->sharing_ratio = $sharing_ratio;
            } else {
                $userModel->sharing_ratio = 0;
            }

            // 更改账号类型字段
            switch ($account_type) {
                case 1;
                    $userModel->is_anchor   = 0;
                    $userModel->anchor_type = 1;
                    break;
                case 2;
                    $userModel->is_anchor   = 0;
                    $userModel->anchor_type = 3;
                    break;
                case 3;
                    $userModel->is_anchor   = 1;
                    $userModel->anchor_type = 1;
                    break;
                case 4;
                    $userModel->is_anchor   = 1;
                    $userModel->anchor_type = 2;
                    break;
                case 5;
                    $userModel->is_anchor   = 1;
                    $userModel->anchor_type = 3;
                    break;
            }

            if ($tags != '') {
                $userModel->tags = $tags;
            }


            try {
                Db::startTrans();

                // 如果是专家角色，添加基本信息到专家表中
                if ($userModel->expert_type == 0 && in_array($expert_type, [1, 2])) {
                    $userModel->expert_type = $expert_type;

                    // 检测专家昵称是否存在
                    $find_nickname_where = [['nick_name', '=', $nick_name]];
                    $check_nickname      = ExpertModel::where($find_nickname_where)->field('id')->find();
                    if (!empty($check_nickname)) {
                        return self::bulidFail("专家昵称已被占用");
                    }

                    $expert_obj = new ExpertModel([
                        'user_id'     => $userModel->id,
                        'profile'     => $userModel->avatar,
                        'nick_name'   => $userModel->nick_name,
                        'create_time' => time(),
                        'grade'       => 1,
                        'admin_id'    => $this->admin_id,
                    ]);
                    if (!$expert_obj->save()) {
                        throw new \Exception('添加信息失败');
                    }
                }

                if (!$userModel->save()) {
                    throw new \Exception('添加信息失败');
                }

                // 修改直播信息
                $live_model = LiveModel::where('anchorid', $userModel->id)->field('id,anchor_name,anchor_avatar')->find();
                if ($live_model) {
                    $live_model->anchor_name   = $userModel->nick_name;
                    $live_model->anchor_avatar = $userModel->avatar;
                    if (!$live_model->save()) {
                        throw new \Exception('基本信息修改失败');
                    }
                }

                if ($userModel->is_anchor == 1) {
                    // 设置es 主播数据
                    $res = UserService::setAnchorEs($userModel->id);
                    if ($res['code'] != 0) {
                        throw new \Exception('修改信息失败');
                    }
                } else {
                    // 不是主播则删除es数据
                    UserService::delAnchorEs($userModel->id);
                }

                // 清理主播缓存
                UserModel::delAnchorCache();

                // 清理快速登录缓存
                if ($pwd) {
                    UserModel::delFastLoginCache($userModel->id);
                }

                // 记录日志
                $log_content = "修改了用户基本信息，用户ID：{$userModel->id}";
                parent::addAdminLog($log_content, $userModel->id);

                UserModel::delUserCache($userModel->id);

                Db::commit();
                return self::bulidSuccess([], "编辑成功");
            } catch (\Exception $e) {
                Db::rollback();
                return self::bulidFail($e->getMessage());
            }
        } else {
            $apply_data = array();
            // 修改了昵称
            if ($userModel->nick_name != $nick_name) {
                $apply_data[] = $this->makeUserApplyData($id, $userModel->nick_name, $nick_name, 0, $remark);

                $userModel->nick_name = $nick_name;
            }

            // // 修改了手机号
            // if ($userModel->mobile != $mobile) {
            //     $apply_data[] = $this->makeUserApplyData($id, $userModel->mobile, $mobile, 1, $remark);
            // }

            // 修改了头像
            if ($userModel->avatar != $avatar) {
                $userModel->avatar = $avatar;
                // $apply_data[] = $this->makeUserApplyData($id, $userModel->avatar, $avatar, 2, $remark);
            }

            // 修改了账号类型
            if ($old_account_type != $account_type) {
                $apply_data[] = $this->makeUserApplyData($id, $old_account_type, $account_type, 3, $remark);
            }

            // 如果不是超管，则添加到信息审核表中，审核操作后方能修改
            // 密码修改和分红直接修改
            try {
                Db::startTrans();

                // 如果是专家角色，添加基本信息到专家表中
                if ($userModel->expert_type == 0 && in_array($expert_type, [1, 2])) {
                    $userModel->expert_type = $expert_type;

                    // 检测专家昵称是否存在
                    $find_nickname_where = [['nick_name', '=', $nick_name]];
                    $check_nickname      = ExpertModel::where($find_nickname_where)->field('id')->find();
                    if (!empty($check_nickname)) {
                        return self::bulidFail("专家昵称已被占用");
                    }

                    $expert_obj = new ExpertModel([
                        'user_id'     => $userModel->id,
                        'profile'     => $userModel->avatar,
                        'nick_name'   => $userModel->nick_name,
                        'create_time' => time(),
                        'grade'       => 1,
                        'admin_id'    => $this->admin_id,
                    ]);
                    if (!$expert_obj->save()) {
                        throw new \Exception('添加信息失败');
                    }
                }


                $userModel->sharing_ratio = $sharing_ratio;
                if ($pwd) {
                    $userModel->password = openssl_encrypt(substr($userModel->account, strlen($userModel->account) - 4, 4) . $pwd, "DES-ECB", $this->OPENSSL_KEY);;
                }

                if (!$userModel->save()) {
                    throw new \Exception('基本信息修改失败');
                }

                // 修改直播信息
                $live_model = LiveModel::where('anchorid', $userModel->id)->field('id,anchor_name,anchor_avatar')->find();
                if ($live_model) {
                    $live_model->anchor_name   = $userModel->nick_name;
                    $live_model->anchor_avatar = $userModel->avatar;
                    if (!$live_model->save()) {
                        throw new \Exception('基本信息修改失败');
                    }
                }

                // 添加修改信息到审核表
                if ($apply_data) {
                    $userApplyModel = new UserApplyModel();
                    $res            = $userApplyModel->insertAll($apply_data);
                    if ($res === false) {
                        throw new \Exception('基本信息修改失败');
                    }
                }

                // 清理快速登录缓存
                if ($pwd) {
                    UserModel::delFastLoginCache($userModel->id);
                }

                Db::commit();
                return self::bulidSuccess([], $apply_data ? "成功提交到信息审核中，请在信息审核中操作" : '修改成功');
            } catch (\Exception $e) {
                Db::rollback();
                return self::bulidDataFail(['error' => $e->getMessage()]);
            }
        }

        return self::bulidFail();
    }

    /**
     *  组合信息审核数据
     * @param $user_id 用户id
     * @param $original 原始数据
     * @param $new 新数据
     * @param $type 修改类型 0:昵称，1:手机，2：头像
     * @param $remark 备注
     * @return array
     */
    private function makeUserApplyData($user_id, $original, $new, $type, $remark)
    {
        $data = array(
            'user_id'       => $user_id,
            'original_data' => $original,
            'new_data'      => $new,
            'change_type'   => $type,
            'status'        => 0,
            'change_source' => 0,
            'remark'        => $remark,
            'created_at'    => date('Y-m-d H:i:s'),
        );
        return $data;
    }


    //封号/解封
    public function del_post()
    {
        $uid    = Request::param("id");
        $status = Request::param("status");

        $userModel = UserModel::get($uid);
        if (!$userModel) {
            return self::bulidFail("参数错误");
        }
        if ($userModel->status == 5) {
            return self::bulidFail("注销状态的用户不可操作");
        }

        $data  = [
            'status'           => $status,
            'banned_num'       => 0,
            'block_until_time' => '0000-00-00 00:00:00',
        ];
        $model = UserModel::where('id', $uid);

        $log_content = '';
        if ($status == 1) {
            $log_content = "封禁用户" . $userModel->nick_name . "(" . $userModel->id . ")";
        } else {
            $log_content = "解封用户" . $userModel->nick_name . "(" . $userModel->id . ")";
        }

        $res = $model->update($data);

        if ($res !== false) {
            // 清理主播缓存
            if ($userModel->is_anchor == 1) {
                UserModel::delAnchorCache();
            }

            // 封禁用户调取grpc
            if ($status == 1) {
                $account_server = new AccountServer();
                $account_server->logout($uid, 1);
            }

            // 记录日志
            parent::addAdminLog($log_content, $uid);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function getReportList()
    {
        $page  = Request::param("page");
        $limit = Request::param("limit");
        $res   = AnchorReportModel::with(['user', 'anchor'])->order('create_time', 'desc')->limit(($page - 1) * $limit, $limit)->select();
        if (count($res) > 0) {
            $count = AnchorReportModel::count('id');
            return json(["code" => 0, "msg" => "", "data" => $res, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    //设为房间管理
    public function setAdmin()
    {
        $uid = Request::param("id");
        if (!$uid) {
            return self::bulidFail("uid不能为空");
        }
        $room_type = Request::param("room_type", 0);

        $user_info = UserModel::get($uid);
        if (!$user_info) {
            return self::bulidFail("用户不存在");
        }

        $userBanne = new LiveRoomManagerModel();
        $find      = $userBanne->where("mgrid", $uid)->find();
        $data      = [
            "anchorid"    => 0,
            "mgrid"       => $uid,
            "type"        => $room_type,
            "create_time" => date('Y-m-d H:i:s'),
        ];
        if ($find) {
            $data["id"] = $find["id"];
        }
        $ret = $userBanne->create($data, "", true);
        GroupChatUserModel::where('user_id', $uid)->update(['role' => 1]);
        if ($ret !== false) {
            // 记录日志
            $log_content = "设置用户({$uid})为房管";
            parent::addAdminLog($log_content, $uid);

            Cache::store('redis')->rm("chat_client_user:" . $uid);
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    //删除房管
    public function delRoomManager()
    {
        $id = Request::param("id");

        if (!$room_manager = LiveRoomManagerModel::where('id', $id)->find()) {
            return static::bulidFail();
        }

        if ($room_manager->delete()) {
            GroupChatUserModel::update(['role' => 0], ['user_id' => $room_manager->mgrid, 'role' => 1]);
            // 记录日志
            $log_content = "删除房管，用户({$room_manager->mgrid})";
            parent::addAdminLog($log_content, $room_manager->mgrid);

            Cache::store('redis')->rm("chat_client_user:" . $room_manager->mgrid);
            return static::bulidSuccess();
        }

        return static::bulidFail();
    }


    //房间管理
    public function getRoomAminList()
    {
        $page  = Request::param("page");
        $limit = Request::param("limit");
        $uid   = Request::param("id");
        $where = [];
        if ($uid) {
            $where['mgrid'] = $uid;
        }
        $res = LiveRoomManagerModel::where($where)->order('id', 'desc')->limit(($page - 1) * $limit, $limit)->select();
        if (count($res) > 0) {
            $count = LiveRoomManagerModel::count('id');
            return json(["code" => 0, "msg" => "", "data" => $res, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    //禁言列表
    public function getBannedList()
    {
        $page       = Request::param("page");
        $limit      = Request::param("limit");
        $uid        = Request::param("uid");
        $anchorid   = Request::param("anchorid");
        $ban_type   = Request::param("ban_type");
        $nick_name  = Request::param("nick_name");
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        // 管理员
        $manager_id = Request::param("manager_id");

        $where = [
            ['ban_time', '>', time()]
        ];
        if ($uid) {
            $where[] = ['uid', '=', is_numeric($uid) ? $uid : 0];
        }
        if ($anchorid) {
            $where[] = ['anchorid', '=', is_numeric($anchorid) ? $anchorid : -1];
        }
        if ($ban_type) {
            $where[] = ['ban_type', '=', is_numeric($ban_type) ? $ban_type : -1];
        }
        if ($nick_name) {
            $search_uid = UserModel::whereLike('nick_name', "%{$nick_name}%")->column('id');
            $where[]    = ['uid', 'IN', $search_uid ?: [-1]];
        }
        if ($manager_id) {
            if (is_numeric($manager_id)) {
                $where[] = ['mgrid', '=', $manager_id];
            } else {
                $search_uid = AdminModel::whereLike('name', "%{$manager_id}%")->column('id');
                $where[]    = ['admin_id', 'IN', $search_uid ?: [-1]];
            }
        }

        if ($start_time) {
            $where[] = ['create_time', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['create_time', '<=', $end_time];
        }

        $res = LiveRoomBanneduserModel::with([
            'user',
            'admin' => function ($query) {
                $query->field('id,name');
            }
        ])->where($where)
            ->order('id', 'desc')
            ->page($page, $limit)
            ->select();

        if (count($res) > 0) {
            foreach ($res as &$item) {
                if ($item->ban_time >= 4294967295) {
                    $item->ban_time_format = '永久';
                } else {
                    $item->ban_time_format = $item->ban_time > 0 ? date('Y-m-d H:i:s', $item->ban_time) : '永久';
                }

                //$item->ban_reason = LiveRoomBanneduserModel::getBanTypeText($item->ban_type);
                $item->ban_reason = $item->reason;

                // 1房管，2主播，3后台管理员
                $item->manager_type = 0;
                $item->manager_name = '';

                if ($item->mgrid > 0) {
                    $item->manager_type = 1;
                    $item->manager_name = $item->mgrid;
                }

                if ($item->admin_id > 0 && $item->mgrid == 0) {
                    $item->manager_type = 3;
                    $item->manager_name = $item->admin ? $item->admin->name : $item->admin_id;
                } else if ($item->mgrid > 0 && $item->anchorid == $item->mgrid) {
                    $item->manager_type = 2;
                }
            }

            $count = LiveRoomBanneduserModel::where($where)->count('id');

            return json(["code" => 0, "msg" => "", "data" => $res, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    //禁言
    public function setBanned()
    {
        $uid      = Request::param("id");
        $room_id  = Request::param("room_id", 0, 'intval');
        $chat_id  = Request::param("chat_id", 0, 'intval');
        $ban_time = Request::param("ban_time", 0);
        $ban_type = Request::param("ban_type");

        if (!$uid) {
            return self::bulidFail("uid不能为空");
        }
        if (!in_array($ban_type, array_keys(LiveRoomBanneduserModel::BAN_TYPE))) {
            return self::bulidFail("请正确选择禁言原因");
        }

        if (!$user_model = UserModel::get($uid)) {
            return self::bulidFail("用户不存在");
        }

        // 查询es数据，获取聊天内容
        $log_chat_str = '';
        if ($chat_id > 0) {
            $chat_data    = ChatService::getChatInfoById($chat_id, $room_id);
            $log_chat_str = !empty($chat_data['content']) ? "，内容：{$chat_data['content']}" : '';
        }

        // 日志内容
        $log_content = "禁言用户，用户ID：{$uid}{$log_chat_str}，原因：" . LiveRoomBanneduserModel::getBanTypeText($ban_type) . '，禁言时长：';
        // 腾讯im禁言时长
        $banned_time = 4294967295;
        switch ($ban_time) {
            case 0:
                $ban_time    = $banned_time;
                $log_content .= '永久禁言';
                break;
            case 1:
                $banned_time = 30 * 60;
                $log_content .= '禁言30分钟';
                $ban_time    = strtotime("+30 minutes", time());
                break;
            case 2:
                $banned_time = 2 * 3600;
                $log_content .= '禁言2小时';
                $ban_time    = strtotime("+2 hours", time());
                break;
            case 3:
                $banned_time = 6 * 3600;
                $log_content .= '禁言6小时';
                $ban_time    = strtotime("+6 hours", time());
                break;
            case 4:
                $banned_time = 1 * 3600 * 24;
                $log_content .= '禁言1天';
                $ban_time    = strtotime("+1 day", time());
                break;
            case 5:
                $banned_time = 7 * 3600 * 24;
                $log_content .= '禁言7天';
                $ban_time    = strtotime("+7 days", time());
                break;
            case 6:
                $banned_time = 10 * 60;
                $log_content .= '禁言10分钟';
                $ban_time    = strtotime("+10 minutes", time());
                break;
        }

        if ($userBanne = LiveRoomBanneduserModel::where('uid', $uid)->find()) {
            if ($userBanne->ban_time < 0 || $userBanne->ban_time > time()) {
                return self::bulidFail('该用户已是禁言状态!');
            }
        } else {
            $userBanne = new LiveRoomBanneduserModel();
        }

        $userBanne->uid = $uid;
        $userBanne->anchorid = 0;
        $userBanne->mgrid = 0;
        $userBanne->admin_id = $this->admin_id;
        $userBanne->ban_time = $ban_time;
        $userBanne->ban_type = $ban_type;
        $userBanne->ban_msg = !empty($chat_data['content']) ? $chat_data['content'] : '';
        $userBanne->reason = LiveRoomBanneduserModel::getBanTypeText($ban_type);
        $userBanne->create_time = date('Y-m-d H:i:s');

        Db::startTrans();
        LiveRoomBanneduserModel::startTrans();
        try {
            if (!$userBanne->save()) {
                throw new \Exception('禁言失败');
            }

            // 记录表日志
            if (parent::addAdminLog($log_content, $uid) < 1) {
                throw new \Exception('日志插入失败');
            }

            $live_server = new LiveServer();
            $res         = $live_server->banUserAllChatAdmin($user_model->id, $user_model->nick_name, $room_id, 1, $banned_time, $userBanne->reason);
            if (!$res) {
                throw new \Exception('禁言失败,调取grpc失败');
            }

            Db::commit();
            LiveRoomBanneduserModel::commit();
            return self::bulidSuccess($room_id > 0 ? '只有在指定房间中禁言用户，才会删除该房间里的历史消息' : '禁言成功');
        } catch (\Exception $e) {
            Db::rollback();
            LiveRoomBanneduserModel::rollback();
            $data['error_msg'] = $e->getMessage();
            writeLog($data, 'band_user_error.txt');
            return self::bulidDataFail(['error' => $e->getMessage()], '禁言失败');
        }

        return self::bulidFail('禁言失败');
    }

    //解除禁言
    public function unBanned()
    {
        $id      = Request::param("id");
        $room_id = Request::param("room_id", '0', 'intval');

        $room_banned_user = LiveRoomBanneduserModel::get($id);
        if (!$room_banned_user) {
            return self::bulidFail('信息不存在');
        }

        $user_model = UserModel::field('id,nick_name')->get($room_banned_user->uid);
        if (!$user_model) {
            return self::bulidFail('用户信息不存在');
        }

        // 解除用户禁言，防止一个用户有多条记录
        if ($room_banned_user->anchorid > 0) {
            $where = ['id' => $id];
        } else {
            $where = ['uid' => $room_banned_user->uid];
        }

        // 这个地方是风控禁言，解禁是全局解禁，grpc不传值room_id
        if ($room_banned_user->ban_type == 9) {
            $room_banned_user->anchorid = 0;
        }

        LiveRoomBanneduserModel::startTrans();
        try {
            $res = LiveRoomBanneduserModel::where($where)->delete();
            if (!$res) {
                throw new \Exception('解除失败，请重试');
            }

            // 调取解除禁言grpc
            $live_server = new LiveServer();
            $res         = $live_server->banUserAllChatAdmin($user_model->id, $user_model->nick_name, $room_banned_user->anchorid, 2, 0);
            if (!$res) {
                throw new \Exception('调取grpc失败，请重试');
            }

            // 清理主播缓存
            UserModel::delAnchorCache();

            LiveRoomBanneduserModel::commit();

            // 记录日志
            $log_content = "解除用户禁言，用户ID：{$room_banned_user->uid}";
            parent::addAdminLog($log_content, $room_banned_user->uid);

            return self::bulidSuccess();
        } catch (\Exception $e) {
            LiveRoomBanneduserModel::rollback();
            return self::bulidDataFail(['error' => $e->getMessage()]);
        }

        return self::bulidFail();
    }


    // 昵称审核
    public function nickname_review()
    {
        return $this->fetch();
    }

    public function nickname_review_list()
    {
        $searchid      = Request::param("id");
        $searchaccount = Request::param("account");
        $status        = Request::param("status", 0);
        $where         = [];
        if ($searchid) {
            $where["id"] = $searchid;
        }
        if ($searchaccount != '') {
            $where["account"] = $searchaccount;
        }
        if (isset($status)) {
            $where["pending_status"] = $status;
        }
        $page     = Request::param("page");
        $limit    = Request::param("limit");
        $userlist = [];
        if ($status == 0) {
            $userlist = UserModel::field("*, from_unixtime(apply_name_time, '%Y-%m-%d %H:%i:%s') as apply_time")->where($where)->where("pending_nick_name", "<>", "")->limit(($page - 1) * $limit, $limit)->order("apply_name_time", "desc")->select();
        } else {
            $userlist = UserModel::alias('u')->field("u.*, from_unixtime(u.apply_name_time, '%Y-%m-%d %H:%i:%s') as apply_time, db_admin.name as admin_name, db_admin.account as admin_account")->join('db_admin', 'db_admin.id = u.pending_admin_id')->where($where)->where("pending_nick_name", "<>", "")->limit(($page - 1) * $limit, $limit)->order("apply_name_time", "desc")->select();
        }
        if (count($userlist) > 0) {
            $count = UserModel::where($where)->where("pending_nick_name", "<>", "''")->count("id");
            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function set_nickname_review()
    {
        $uid      = Request::param("uid");
        $status   = Request::param("status");
        $nickname = Request::param("nickname");
        if ($status == 1) {
            $update = UserModel::where("id", $uid)->update(['nick_name' => $nickname, 'pending_status' => $status, 'pending_admin_id' => Cookie::get("uid")]);
            $update = LiveModel::where("anchorid", $uid)->update(['anchor_name' => $nickname]);     // 更新正在直播中的用户昵称如果存在
            if ($update) {
                return self::bulidSuccess([], "操作成功");
            } else {
                return self::bulidFail();
            }
        }

        if ($status == 2) {
            $update = UserModel::where("id", $uid)->update(['pending_status' => $status, 'pending_admin_id' => Cookie::get("uid")]);
            if ($update) {
                return self::bulidSuccess([], "操作成功");
            } else {
                return self::bulidFail();
            }
        }
    }

    public function anchor()
    {
        return $this->assign([
            // etype市场专用类型判断，1为市场专用
            'etype'      => Request::get('etype', 0, 'intval'),
        ])->fetch();
    }

    public function anchor_list()
    {
        $order = Request::param("order");

        $searchid       = Request::param("id");
        $searchname     = Request::param("nick_name");
        $searchisanchor = Request::param("is_anchor");
        $searchisonline = Request::param("online_status");
        // 主播状态  1禁播
        $anchor_status = Request::param("anchor_status");
        // $searchvip = Request::param('vip_level');
        $searchaccount = Request::param("account");
        $mobile        = Request::param("mobile");
        $regist_type   = Request::param("regist_type");
        $start_time    = Request::param("start_time");
        $end_time      = Request::param("end_time");

        $where = [
            ['is_anchor', '=', 1]
        ];

        if ($searchid) {
            $where[] = ['id', '=', $searchid];
        }
        if ($searchname) {
            $where[] = ['nick_name', '=', $searchname];
        }
        if ($searchisanchor != '') {
            $where[] = ['is_anchor', '=', $searchisanchor];
        }
        if ($searchaccount != '') {
            $where[] = ['account', '=', $searchaccount];
        }
        if ($mobile != '') {
            $where[] = ['mobile', '=', $mobile];
        }
        if ($regist_type != '') {
            $where[] = ['regist_type', '=', $regist_type];
        }
        if ($start_time != '') {
            $where[] = ["auth_time", ">", $start_time];
        }
        if ($end_time != '') {
            $where[] = ["auth_time", "<=", $end_time];
        }

        // 禁播用户查询
        if ($anchor_status == 1) {
            $banned_uid = AnchorBannedModel::where('ban_time', 0)->whereOr('ban_time', '>=', time())->column('anchor_id');
            if ($banned_uid) {
                $where[] = ['id', 'in', $banned_uid];
            } else {
                // 没有禁播的时候
                $where[] = ['id', '=', 0];
            }
        }

        if ($order == '') {
            $order = ['regist_time' => 'desc'];
        } else {
            $order = ['auth_time' => $order];
        }

        $page  = Request::param("page");
        $limit = Request::param("limit");

        // 正在直播中的
        if ($searchisonline != '') {
            $in_live_ids = LiveModel::column('anchorid');
            $in_live_ids = !empty($in_live_ids) ? $in_live_ids : [0];
            if ($searchisonline == 1) {
                $where[] = ['id', 'in', $in_live_ids];
            } else if ($searchisonline == 2) {
                $where[] = ['id', 'not in', $in_live_ids];
            }
        }

        $userlist = UserModel::where($where)->with(['inLive', 'anchorAuth', 'guild', 'anchorLiveNotice', 'anchorBanned' => function ($query) {
            $query->where('ban_time', 0)->whereOr('ban_time', '>=', time());
        }, 'recommend'                                                                                                  => function (Query $query) {
            $query->field('user_id,total_recommend,total_noble');
        }])->limit(($page - 1) * $limit, $limit)->order($order)->select();

        if (count($userlist) > 0) {
            $count = UserModel::where($where)->count("id");

            // 查询粉丝数
            $anchorid_arr = array_column($userlist->toArray(), 'id');
            $anchorid_arr = array_filter(array_unique($anchorid_arr));
            $fans_count   = AnchorFansModel::whereIn('anchorid', $anchorid_arr)->field('anchorid,count(id) as total')->group('anchorid')->select()->toArray();
            $fans_count   = array_column($fans_count, 'total', 'anchorid');

            foreach ($userlist as &$value) {

                $value['advertising'] = stripslashes($value['advertising']);
                $value["mobile"]      = mobileHide($value['mobile'], $this->userinfo->roleid);
                $value["account"]     = mobileHide($value['account'], $this->userinfo->roleid);
                $value['tag'] = ConfigTagModel::get($value['tags'])['title'] ?? '';

                // 粉丝数
                $value['fans_count'] = isset($fans_count[$value['id']]) ? $fans_count[$value['id']] : 0;

                if (empty($value["anchor_banned"])) {
                    continue;
                }

                $time = $value["anchor_banned"]["ban_time"] - time();
                if ($time > 0) {
                    $date = [
                        'day'    => intval($time / (24 * 3600)),
                        'hour'   => intval(($time % (24 * 3600)) / 3600),
                        'minute' => intval((($time % (24 * 3600)) % 3600) / 60),
                    ];

                    $value["anchor_banned"]["ban_time_format"] = "{$date['day']}天{$date['hour']}时{$date['minute']}分";
                } else if ($value["anchor_banned"]["ban_time"] == 0) {
                    $value["anchor_banned"]["ban_time_format"] = "永久";
                } else {
                    $value["anchor_banned"]["ban_time_format"] = "";
                }
            }

            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function anchor_set_banned()
    {
        $id        = Request::param("id");
        $userModel = UserModel::get($id);
        $this->assign("userinfo", $userModel);
        return $this->fetch();
    }

    public function save_anchor_banned()
    {
        $id     = Request::param("id");
        $time   = intval(Request::param("time"));
        $reason = Request::param("reason");

        // 禁播时长
        $ban_time = empty($time) ? 0 : strtotime("+ $time days");

        $data = [
            'anchor_id'    => $id,
            "admin_id"     => Cookie::get("uid"),
            "reason"       => htmlspecialchars($reason),
            "ban_time"     => $ban_time,
            "created_time" => time(),
        ];

        AnchorBannedModel::where(["anchor_id" => $id])->delete();
        $r = AnchorBannedModel::create($data);
        if ($r) {
            // 删除主播缓存
            UserModel::delAnchorCache();

            // 记录日志
            $log_content = "设置主播禁播，主播ID：{$id}，禁播时长：" . (empty($time) ? '永久' : $time . '天');
            parent::addAdminLog($log_content, $id);

            return self::bulidSuccess();
        }
        return self::bulidFail("操作失败");
    }

    public function anchor_unbanned()
    {
        $id = Request::param("id");
        $r  = AnchorBannedModel::where(["anchor_id" => $id])->delete();
        if ($r) {
            // 删除主播缓存
            UserModel::delAnchorCache();

            // 记录日志
            $log_content = "取消主播禁播，主播ID：{$id}";
            parent::addAdminLog($log_content, $id);

            return self::bulidSuccess();
        }
        return self::bulidFail("操作失败");
    }

    /**
     * 用户背包
     */
    public function backpack()
    {
        if (!$uid = $this->request->param('uid')) {
            return static::bulidFail('用户ID不能为空');
        }

        if ($this->request->isAjax()) {
            $model = UserBackpackStatistics::field('*')->where('uid', $uid);

            if (is_numeric($type = $this->get('type', '-1')) && $type > -1) {
                $model = $model->where('type', $type);
            }

            return json([
                "count" => $model->count('id'),
                "list"  => $model->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()
                    ->toArray(),
                "code"  => 0,
                "msg"   => "",
            ]);
        }

        return $this->assign(['uid' => $uid])->fetch();
    }

    public function getBackpackListBak()
    {
        $uid = Request::param("uid");
        // 0收费礼物，1=免费
        $type  = Request::param("type", 0);
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $where = [['uid', '=', $uid], ['used', '=', 0]];
        if ($type > 0) {
            $where[] = ['price', '=', 0];
        } else {
            $where[] = ['price', '>', 0];
        }

        $list = UserBackpackModel::where($where)->alias('a')
            ->field('*,count(*) as count,gift.title,gift.price')
            ->Join(config('database.db_live.database') . '.db_gift gift', 'gift.id = a.gid')
            ->limit(($page - 1) * $limit, $limit)
            ->group('gid')
            ->order('count DESC')
            ->select()
            ->each(function ($query) {
                if ($query->price > 0) {
                    $query->price = bcdiv(strval($query->price), '100', 2);
                }
            });

        if (count($list) > 0) {
            $count = UserBackpackModel::where($where)->alias('a')
                ->Join(config('database.db_live.database') . '.db_gift gift', 'gift.id = a.gid')
                ->group('gid')
                ->count();

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function advertising()
    {
        if (!ctype_digit($id = $this->get('id'))) {
            return static::bulidFail("主播ID错误");
        }

        if (!$model = UserModel::field('id, advertising')->where('is_anchor', 1)->where('id', $id)->find()) {
            return static::bulidFail("主播不存在");
        }

        if ($this->request->isAjax()) {
            $content           = trim($this->post('content', ''));
            $main_content           = trim($this->post('main_content', ''));
            $contact_name_1    = strtoupper(trim($this->post('contact_name_1', '')));
            $contact_name_2    = strtoupper(trim($this->post('contact_name_2', '')));
            $contact_name_3    = strtoupper(trim($this->post('contact_name_3', '')));
            $contact_address_1 = trim($this->post('contact_address_1', ''));
            $contact_address_2 = trim($this->post('contact_address_2', ''));
            $contact_address_3 = trim($this->post('contact_address_3', ''));

            if (!$contact_name_1) {
                if ($contact_address_1) {
                    return static::bulidFail('联系方式名称不能为空');
                }
            } else {
                if (!$contact_address_1) {
                    return static::bulidFail('联系方式地址不能为空');
                }
            }

            if (!$contact_name_2) {
                if ($contact_address_2) {
                    return static::bulidFail('联系方式名称不能为空');
                }
            } else {
                if (!$contact_address_2) {
                    return static::bulidFail('联系方式地址不能为空');
                }
            }

            if (!$contact_name_3) {
                if ($contact_address_3) {
                    return static::bulidFail('联系方式名称不能为空');
                }
            } else {
                if (!$contact_address_3) {
                    return static::bulidFail('联系方式地址不能为空');
                }
            }

            if (mb_strlen($content) > 200) {
                return static::bulidFail('屏幕广告字符限制200个字符内');
            }

            if (mb_strlen($contact_name_1) > 50) {
                return static::bulidFail('联系方式名称字符限制22个字符内');
            }

            if (mb_strlen($contact_address_1) > 50) {
                return static::bulidFail('联系方式地址字符限制22个字符内');
            }

            if (mb_strlen($contact_name_2) > 50) {
                return static::bulidFail('联系方式名称字符限制22个字符内');
            }

            if (mb_strlen($contact_address_2) > 50) {
                return static::bulidFail('联系方式地址字符限制22个字符内');
            }

            if (mb_strlen($contact_name_3) > 50) {
                return static::bulidFail('联系方式名称字符限制22个字符内');
            }

            if (mb_strlen($contact_address_3) > 50) {
                return static::bulidFail('联系方式地址字符限制22个字符内');
            }

            if (mb_strlen($main_content) > 70) {
                return static::bulidFail('主播字符限制70个字符内');
            }

            try {
                if ($notice = LiveNoticeModel::where('anchorid', $model->id)->where('type', 1)->find()) {
                    $notice->content           = $content;
                    $notice->contact_name_1    = $contact_name_1;
                    $notice->contact_address_1 = $contact_address_1;
                    $notice->contact_name_2    = $contact_name_2;
                    $notice->contact_address_2 = $contact_address_2;
                    $notice->contact_name_3    = $contact_name_3;
                    $notice->contact_address_3 = $contact_address_3;
                    $notice->manager_id        = $this->admin_id;
                    $notice->create_time       = date('Y-m-d H:i:s');
                    $notice->main_content       = $main_content;


                    $res = $notice->save();
                } else {
                    $res = LiveNoticeModel::create([
                        'content'           => $content,
                        'contact_name_1'    => $contact_name_1,
                        'contact_address_1' => $contact_address_1,
                        'contact_name_2'    => $contact_name_2,
                        'contact_address_2' => $contact_address_2,
                        'contact_name_3'    => $contact_name_3,
                        'contact_address_3' => $contact_address_3,
                        'create_time'       => date('Y-m-d H:i:s'),
                        'type'              => 1,
                        'anchorid'          => $model->id,
                        'manager_id'        => $this->admin_id,
                        'main_content'      => $main_content,
                    ]);
                }

                if (!$res) {
                    throw new \Exception('公告调整失败');
                }

                $model->advertising = $content;
                if (!$model->save()) {
                    throw new \Exception('屏幕广告修改失败');
                }

                // 联系方式
                $contact_json = json_encode([
                    ['title' => $contact_name_1, 'value' => $contact_address_1],
                    ['title' => $contact_name_2, 'value' => $contact_address_2],
                    ['title' => $contact_name_3, 'value' => $contact_address_3],
                    ['title' => 'main_content', 'value' => $main_content],
                ]);

                /**grpc调取*/
                $live_server = new LiveServer();
                $res         = $live_server->roomBoardcast($model->id, $content, $contact_json);
                if (!$res) {
                    throw new \Exception('调用grpc接口失败');
                }

                /**记录日志*/
                $log_content = "修改屏幕广告，主播ID：{$model->id}，内容：{$model->advertising}";
                parent::addAdminLog($log_content, $model->id);

                return static::bulidSuccess([], '编辑成功');
            } catch (\Exception $e) {
                return self::bulidDataFail(['error' => $e->getMessage()], '修改失败');
            }

            return self::bulidFail("修改失败");
        }

        $notice = LiveNoticeModel::where('anchorid', $model->id)->where('type', 1)->find();

        $model->content           = $notice->content ?? '';
        $model->contact_name_1    = $notice->contact_name_1 ?? '';
        $model->contact_address_1 = $notice->contact_address_1 ?? '';
        $model->contact_name_2    = $notice->contact_name_2 ?? '';
        $model->contact_address_2 = $notice->contact_address_2 ?? '';
        $model->contact_name_3    = $notice->contact_name_3 ?? '';
        $model->contact_address_3 = $notice->contact_address_3 ?? '';
        $model->main_content = $notice->main_content ?? '';

        return $this->assign(['model' => $model])->fetch();
    }

    public function login_log()
    {
        if ($this->request->isAjax()) {
            if (!ctype_digit($uid = $this->get('uid'))) {
                return static::bulidFail('用户ID错误');
            }

            $model = UserLogModel::field('uid,create_time,device,last_ip,login_platform')->where('uid', $uid);

            return json([
                'count' => $model->count('id'),
                'list' => $model->order('create_time', 'desc')
                    ->page((int)$this->get('page', 1), (int)$this->get('limit', 20))
                    ->select()
                    ->toArray(),
                'code' => 0,
            ]);
        }
        return $this->assign([
            'uid' => $this->request->param('uid'),
        ])->fetch();
    }

    public function device_blacklist()
    {
        if (!ctype_digit($id = $this->post('id'))) {
            return static::bulidFail('用户ID错误');
        }

        if (!in_array($status = $this->post('status'), ['1', '2'])) {
            return static::bulidFail('参数错误');
        }

        if (!$user = UserModel::field('id,device_info,online_status')->where('id', $id)->find()) {
            return static::bulidFail('用户不存在');
        }

        if (!$user->device_info || !trim($user->device_info)) {
            return static::bulidFail('用户设备信息异常 操作失败');
        }

        if ($status == 1) {
            try {
                if ($user->online_status == 1) {
                    $account_server = new AccountServer();
                    $account_server->logout($id);
                }
            } catch (\Exception $exception) {
            }
            if (BlackDeviceModel::create([
                'device' => $user->device_info,
                'note' => '',
                'add_time' => $time = date('Y-m-d H:i:s'),
                'modify_time' => $time,
                'admin_id' => $this->admin_id
            ])) {
                $this->addAdminLog('拉黑设备并踢出用户,uid:' . $id, $id);
                return static::bulidSuccess([], '设备拉黑成功');
            }

            return static::bulidFail('设备拉黑失败');
        } else {
            if (BlackDeviceModel::where('device', $user->device_info)->delete()) {
                return static::bulidSuccess([], '设备移除黑名单成功');
            }

            return static::bulidFail('设备移除黑名单失败');
        }
    }

    public function ticket()
    {
        if ($this->request->isAjax()) {
            $type = 105;
            if (!ctype_digit($id = $this->post('id')) || $id <= 0) {
                return static::bulidFail('用户ID非法');
            }
            if (!is_numeric($quantity = rtrim(trim($this->post('quantity', '')), '.')) || bccomp($quantity, '0', 2) < 0) {
                return static::bulidFail('请正确输入观赛券数量');
            }
            if (!UserModel::where('id', $id)->field('id, nick_name')->lock()->find()) {
                return static::bulidFail('用户不存在');
            }
            Db::startTrans();
            try {
                $model = UserBackpackStatistics::where('uid', $id)->where('type', $type)->find();
                if ($model) {
                    $model->quantity = bcadd($model->quantity, $quantity);
                    $model->save();
                } else {
                    // 不存在则新增
                    UserBackpackStatistics::create([
                        'uid'      => $id,
                        'gid'      => 9,
                        'price'      => 0,
                        'type'     => $type,
                        'quantity' => $quantity,
                        'product_name'=> '观赛券',
                    ]);
                }
                UserBackpackModel::create([
                    'uid'      => $id,
                    'gid'      => 9,
                    'price'      => 0,
                    'type'     => $type,
                    'create_time' => time(),
                    'quantity' => $quantity,
                    'remark'=> '手动发放',
                ]);
                UserTicketLogModel::create([
                   "uid" => $id,
                   "type" => 5,
                    "num" => $quantity,
                    "date" => date("Y-m-d"),
                    "create_time" => date("Y-m-d H:i:s"),
                ]);

                Db::commit();
                return static::bulidSuccess();
            }catch (\Exception $exception) {
                Db::rollback();
                return static::bulidFail($exception->getMessage());
            }
        }
        return $this->assign([
            'uid' => $this->request->param('uid'),
        ])->fetch();
    }

    /**
     * 用户观赛券发放记录
     * @return mixed
     */
    public function give_ticket_log()
    {
        $uid = Request::param('uid');
        $this->assign('uid', $uid);
        return $this->fetch();
    }

    /**
     * 用户观赛券发放记录
     * @return \think\response\Json
     */
    public function ajax_give_ticket_log()
    {
        $where            = [];
        $where_time_start = '';
        $where_time_end   = '';

        $uid        = Request::param('uid');
        $type       = Request::param('type', 0);
        $time_type = Request::param("time_type", 0);
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        $page       = Request::param("page", 1);
        $limit      = Request::param("limit");

        if ($uid < 1) {
            return self::bulidFail("未查询到相关数据");
        }

        $where["uid"] = $uid;

        if($type) {
            $where["type"] = $type;
        }

        switch ($time_type) {
            case 1:
                // 今日
                $day_time = date('Y-m-d 00:00:00');
                $end_time = date('Y-m-d 23:59:59');
                break;
            case 2:
                // 昨日
                $day_time = date('Y-m-d 00:00:00', strtotime('-1 day'));
                $end_time = date('Y-m-d 23:59:59', strtotime('-1 day'));
                break;
            case 3:
                // 最近7天
                $day_time = date('Y-m-d 00:00:00', strtotime('-7 days'));
                break;
            case 4:
                // 最近30天
                $day_time = date('Y-m-d 00:00:00', strtotime('-30 days'));
                break;
        }

        if (isset($day_time)) {
            $where_time_start = "create_time > '{$day_time}'";
        }
        if ($start_time) {
            $where_time_start = "create_time > '{$start_time}'";
        }
        if ($end_time) {
            $where_time_end = "create_time < '{$end_time}'";
        }
        $logs = UserTicketLogModel::where($where)->where($where_time_start)->where($where_time_end)
            ->limit(($page - 1) * $limit, $limit)
            ->order("create_time", "desc")
            ->select();
        $count  = count($logs);
        if ($count > 0) {
            $count = UserTicketLogModel::where($where)->where($where_time_start)->where($where_time_end)->count("id");
            return json(["code" => 0, "msg" => "", "data" => $logs, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }


    /**
     * 用户观赛券用券记录
     * @return mixed
     */
    public function used_ticket_log()
    {
        $uid = Request::param('uid');
        $this->assign('uid', $uid);
        return $this->fetch();
    }

    /**
     * 用户观赛券用券记录
     * @return \think\response\Json
     */
    public function ajax_used_ticket_log()
    {
        $where            = [];
        $where_time_start = '';
        $where_time_end   = '';

        $uid        = Request::param('uid');
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        $page       = Request::param("page", 1);
        $limit      = Request::param("limit");

        if ($uid < 1) {
            return self::bulidFail("未查询到相关数据");
        }

        $where["uid"] = $uid;
        if ($start_time) {
            $where_time_start = "created_at > '{$start_time}'";
        }
        if ($end_time) {
            $end_time = date('Y-m-d 23:59:59', strtotime($end_time));
            $where_time_end = "created_at < '{$end_time}'";
        }

        $logs = LiveTicketLogModel::where($where)->where($where_time_start)->where($where_time_end)
            ->limit(($page - 1) * $limit, $limit)
            ->order("created_at", "desc")
            ->select();

        $count  = count($logs);
        if ($count > 0) {
            $count = LiveTicketLogModel::where($where)->where($where_time_start)->where($where_time_end)->count("id");
            foreach ($logs as &$item) {
                $item["used_time"] = date("Y-m-d H:i:s", $item["created_at"]);
                $item["expired_time"] = date("Y-m-d H:i:s", $item["created_at"] + 86399);
                $item["num"] = 1;
            }
            return json(["code" => 0, "msg" => "", "data" => $logs, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }


    /**
     * 用户观赛券发放统计
     * @return mixed
     */
    public function stat_ticket_log()
    {
        //今日
        $today = date("Y-m-d");
        $field = " sum(num) as ticket_count, 
        sum(IF(type =2, num, 0)) as register_count ,
        sum(IF(type =3, num, 0)) as signin_count, 
        sum(IF(type =4, num, 0)) as recharge_count, 
        sum(IF(type =5, num, 0)) as customer_count  ";
        $ticket_stat = UserTicketLogModel::where('date', $today)
            ->field($field)
            ->group("date")
            ->find();
        if(empty($ticket_stat)){
            $ticket_stat = [
                "ticket_count" => 0,
                "register_count" => 0,
                "signin_count" => 0,
                "recharge_count" => 0,
                "customer_count" => 0,

            ];
        }
        $this->assign('ticket_stat', $ticket_stat);
        $today_user_count = UserTicketLogModel::where('date', $today)->count('distinct uid');
        $this->assign('today_user_count', $today_user_count);
        $today_register_user_count = UserTicketLogModel::where('date', $today)->where("type", 2)->count('distinct uid');
        $this->assign('today_register_user_count', $today_register_user_count);
        $today_signin_user_count = UserTicketLogModel::where('date', $today)->where("type", 3)->count('distinct uid');
        $this->assign('today_signin_user_count', $today_signin_user_count);
        $today_recharge_user_count = UserTicketLogModel::where('date', $today)->where("type", 4)->count('distinct uid');
        $this->assign('today_recharge_user_count', $today_recharge_user_count);
        $today_customer_user_count = UserTicketLogModel::where('date', $today)->where("type", 5)->count('distinct uid');
        $this->assign('today_customer_user_count', $today_customer_user_count);
        return $this->fetch();
    }

    /**
     * 用户观赛券发放统计
     * @return \think\response\Json
     */
    public function ajax_stat_ticket_log()
    {
        $where            = [];
        $where_time_start = '';
        $where_time_end   = '';

        $type       = Request::param('type', 0);
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        $page       = Request::param("page", 1);
        $limit      = Request::param("limit");


        switch ($type) {
            case 1:
                // 今日
                $day_time = date('Y-m-d 00:00:00');
                $end_time = date('Y-m-d 23:59:59');
                break;
            case 2:
                // 昨日
                $day_time = date('Y-m-d 00:00:00', strtotime('-1 day'));
                $end_time = date('Y-m-d 23:59:59', strtotime('-1 day'));
                break;
            case 3:
                // 最近7天
                $day_time = date('Y-m-d 00:00:00', strtotime('-7 days'));
                break;
            case 4:
                // 最近30天
                $day_time = date('Y-m-d 00:00:00', strtotime('-30 days'));
                break;
        }

        if (isset($day_time)) {
            $where_time_start = "create_time > '{$day_time}'";
        }
        if ($start_time) {
            $where_time_start = "create_time > '{$start_time}'";
        }
        if ($end_time) {
            $where_time_end = "create_time < '{$end_time}'";
        }

        $field = "date, sum(num) as ticket_count, 
            count(DISTINCT uid) as user_count, 
            sum(IF(type =2, num, 0)) as register_count, 
            sum(IF(type =3, num, 0)) as signin_count, 
            sum(IF(type =4, num, 0)) as recharge_count, 
            sum(IF(type =5, num, 0)) as customer_count  ";
        $logs = UserTicketLogModel::where($where)->where($where_time_start)->where($where_time_end)
            ->field($field)
            ->limit(($page - 1) * $limit, $limit)
            ->group("date")
            ->order("date desc,  ticket_count desc")
            ->select();
        $count  = count($logs);
        if ($count > 0) {
            $count = UserTicketLogModel::where($where)->where($where_time_start)->where($where_time_end)->group("date")->count("id");
            return json(["code" => 0, "msg" => "", "data" => $logs, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }


}
